package com.vhans.db.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vhans.core.domain.CGroupMsg;
import com.vhans.core.utils.BeanCopyUtils;
import com.vhans.core.utils.StringUtils;
import com.vhans.db.mapper.CGroupMsgMapper;
import com.vhans.db.model.dto.ConditionDTO;
import com.vhans.db.model.dto.groupmsg.GroupMsgDTO;
import com.vhans.db.model.vo.groupmsg.GroupMsgInfoVO;
import com.vhans.db.model.vo.groupmsg.GroupMsgLastVO;
import com.vhans.db.model.vo.groupmsg.GroupMsgVO;
import com.vhans.db.service.ICGroupMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 群聊天信息Service业务层处理
 *
 * @author vhans
 * @date 2023-05-21
 */
@Service("cGroupMsgServiceImpl")
public class CGroupMsgServiceImpl implements ICGroupMsgService {
    @Autowired
    private CGroupMsgMapper groupMsgMapper;

    @Override
    public List<GroupMsgVO> selectGroupMsgVOList(ConditionDTO condition) {
        return groupMsgMapper.selectGroupMsgVOList(condition);
    }

    @Override
    public CGroupMsg insertGroupMsg(GroupMsgDTO cGroupMsg) {
        // 要添加的群聊天信息
        CGroupMsg newGroupMsg = BeanCopyUtils.copyBean(cGroupMsg, CGroupMsg.class);
        groupMsgMapper.insert(newGroupMsg);
        return newGroupMsg;
    }

    @Override
    public void deleteGroupMsg(Integer msgId) {
        groupMsgMapper.deleteById(msgId);
    }

    @Override
    public GroupMsgInfoVO selectGroupMsgInfoById(Integer id) {
        // 查询群聊天信息信息
        GroupMsgInfoVO cGroupMsgInfoVO = groupMsgMapper.selectGroupMsgInfoById(id);
        Assert.notNull(cGroupMsgInfoVO, "没有该群聊天信息");
        return cGroupMsgInfoVO;
    }

    @Override
    public int deleteGroupMsgByIdIdList(List<Integer> idList) {
        // 删除群聊天信息
        return groupMsgMapper.deleteBatchIds(idList);
    }

    @Override
    public GroupMsgLastVO getLastGroupMsg(Integer groupId) {
        // 查询最后一条消息
        CGroupMsg msg = groupMsgMapper.selectOne(new LambdaQueryWrapper<CGroupMsg>()
                .select(CGroupMsg::getId, CGroupMsg::getGroupId, CGroupMsg::getMsgType, CGroupMsg::getContent)
                .eq(CGroupMsg::getGroupId, groupId)
                .orderByDesc(CGroupMsg::getId));
        if (StringUtils.isNull(msg)) {
            // 空消息
            return GroupMsgLastVO.builder()
                    .id(null)
                    .groupId(groupId)
                    .msgType(1)
                    .content("").build();
        } else {
            return GroupMsgLastVO.builder()
                    .id(msg.getId())
                    .groupId(msg.getGroupId())
                    .msgType(msg.getMsgType())
                    .content(msg.getContent()).build();
        }
    }

    @Override
    public List<GroupMsgVO> getRecentGroupMsg(Integer groupId) {
        return groupMsgMapper.getRecentGroupMsg(groupId);
    }
}
